<template>
  <div style="min-width:829px">
    <div v-if="$route.path == '/projectManagement'">
      <div class="vs-search-box">
        <el-form ref="form" :inline="true" :model="paging" label-width="110px">
          <!-- <el-form-item label="门店：">
                    <el-select v-model="paging.store_id" clearable style="width:200px" placeholder="请选择">
                        <el-option
                            v-for="item in shopList"
                            :key="item.id"
                            :label="item.title"
                            :value="item.id">
                        </el-option>
                    </el-select>
          </el-form-item>-->
          <el-form-item label="项目名称">
            <el-input style="width:200px" v-model="paging.name"></el-input>
          </el-form-item>
          <el-form-item label class="vs-right-btns">
            <el-button @click="reset">重置</el-button>
            <el-button @click="select()" type="primary">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="vs-table-box">
        <div class="operation-box clear-float">
          <el-button
            icon="el-icon-plus"
            @click="itemRow()"
            style="margin-left:auto;"
            type="primary"
          >新增</el-button>
        </div>
        <el-table
          v-loading="loading"
          :data="tableData"
          header-row-class-name="has-gutter-table"
          style="width: 100%"
        >
          <el-table-column prop="name" label="项目名称"></el-table-column>
          <el-table-column prop="tips" label="特别提醒"></el-table-column>
          <el-table-column prop="desc" label="项目介绍"></el-table-column>
          <el-table-column label="启用/禁用">
            <template slot-scope="scope">
              <el-switch
                @change="handleSwitchChange($event, scope.row)"
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
                active-color="#13ce66"
                inactive-color="#ff4949"
              ></el-switch>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="content" label="图文详情">
                     <template slot-scope="scope">
                        <div v-html="scope.row.content"></div>
                    </template>
          </el-table-column>-->
          <el-table-column prop="notice" label="购买须知"></el-table-column>
          <el-table-column prop="pic" label="项目图片">
            <template slot-scope="scope">
              <vs-uploading width="120px" readonly ref="uploading" v-model="scope.row.pic"></vs-uploading>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="pics" label="图片">
                    <template slot-scope="scope">
                        <vs-uploading width="120px" readonly ref="uploading" v-model="scope.row.pics"></vs-uploading>
                    </template>
          </el-table-column>-->
          <el-table-column prop="create_time" label="创建时间"></el-table-column>
          <el-table-column fixed="right" width="109" label="操作">
            <template slot-scope="scope">
              <span @click="setRow(1,scope.row)" class="tab-table-text">编辑</span>
              <span @click="setRow(2,scope.row,scope.$index)" class="tab-red-text">删除</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="vs-paging-box">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page.sync="paging.page"
            :page-size="paging.limit"
            layout="prev, pager, next, jumper"
            :total="paging.total"
          ></el-pagination>
        </div>
      </div>
    </div>

    <router-view></router-view>

    <el-dialog
      :title="(form.id ? '编辑' : '添加') + '项目'"
      :visible.sync="dialogFormVisible"
      width="50%"
      :before-close="closeDialog"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="项目名称：" prop="name" class="ruleFormInput">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="项目分类：" prop="cate_id" class="ruleFormInput">
          <el-select
            v-model="form.cate_id"
            style="width: 30%; min-width: 200px;"
            filterable
            placeholder="请选择项目分类"
          >
            <el-option v-for="item in templateOpts" :key="item.id" :label="item.title" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="封面图:" style="width: 100%" ref="pic" prop="pic">
          <vs-uploading width="120px" @verify="verify('pic', $event)" v-model="form.pic"></vs-uploading>
        </el-form-item>
        <el-form-item label="项目图片:" style="width: 100%" ref="pics" prop="pics">
          <vs-uploading width="120px" @verify="verify('pics', $event)" v-model="form.pics"></vs-uploading>
        </el-form-item>
        <el-form-item label="图文详情：" style="width: 100%" prop="content">
          <div id="edit" ref="edit"></div>
        </el-form-item>
        <el-form-item label="特别提醒：" style="width: 100%" prop="tips">
          <el-input v-model="form.tips" placeholder="请输入" type="textarea" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="购买须知：" style="width: 100%" prop="notice">
          <el-input v-model="form.notice" placeholder="请输入" type="textarea" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="项目介绍：" style="width: 100%" prop="desc">
          <el-input v-model="form.desc" placeholder="请输入" type="textarea" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="addLabel()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import VsUploading from "../../components/VsUploading";
import E from "wangeditor";
export default {
  components: {
    VsUploading
  },
  data() {
    return {
      rules: {
        cate_id: {
          required: true,
          message: "请输选择项目分类",
          trigger: "blur"
        },
        name: { required: true, message: "请输入项目名称", trigger: "change" },
        tips: { required: true, message: "请输入特别提醒", trigger: "change" },
        notice: {
          required: true,
          message: "请输入购买须知",
          trigger: "change"
        },
        pic: { required: true, message: "请上传封面图!", trigger: "blur" },
        pics: { required: true, message: "请上传项目图片!", trigger: "blur" },
        desc: { required: true, message: "请输入项目介绍", trigger: "change" }
      },
      dialogFormVisible: false,
      options: [
        {
          value: "正大店",
          label: "正大店"
        }
      ],
      templateOpts: [],
      recordList: [],
      loading: false,
      paging: {
        page: 1,
        limit: 20,
        total: 0, //总数
        name: ""
      },
      form: {
        url: "",
        name: "",
        id: "",
        pic: "",
        pics: [],
        tips: "",
        desc: "",
        content: "",
        notice: "",
        cate_id: ""
      },
      tableData: [],
      shopList: []
    };
  },
  created() {
    this.GetList();
    this.homegetStore();
    this.getOptions();
  },
  methods: {
    async getOptions() {
      const resp = await this.$Http.getTmpCate({});
      this.templateOpts = resp.data || [];
    },
    handleSwitchChange(status, row) {
      this.$Http
        .saveTmpStatus({
          id: row.id,
          status: status
        })
        .then(res => {
          if (res.code) {
            this.$message({
              type: "success",
              message: "操作成功"
            });
          }
        })
        .finally(() => {
          this.GetList();
        });
    },
    async GetList() {
      let { code, data } = await this.$Http.getProjectTmp({
        page: this.paging.page,
        limit: this.paging.limit,
        name: this.paging.name
      });
      if (code) {
        this.tableData = data.list;
        this.paging.total = data.count;
      }
    },
    closeDialog() {
      this.dialogFormVisible;
    },
    verify(hasFmt, sta) {
      if (sta) {
        this.$refs[hasFmt].validate();
      } else this.$refs[hasFmt].clearValidate();
    },
    itemRow() {
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.getEdit();
      });
    },
    async homegetStore() {
      let { code, data } = await this.$Http.homegetStore();
      if (code) {
        this.shopList = data;
      }
    },
    handleCurrentChange(val) {
      this.paging.page = val;
      this.GetList();
    },
    // 查询
    select() {
      // if(!this.paging.title){
      //     this.utils.message('查询关键字不能为空！')
      //     return false
      // }
      this.GetList();
    },
    async setRow(type, row, index) {
      if (type == 1) {
        this.form.id = row.id;
        this.form.name = row.name;
        this.form.pic = row.pic;
        this.form.pics = row.pics;
        this.form.tips = row.tips;
        this.form.desc = row.desc;
        this.form.content = row.content;
        this.form.notice = row.notice;
        this.form.cate_id = row.cate_id;

        // this.editor.txt.html(row.content);
        this.$nextTick(() => {
          this.getEdit();
        });
        this.dialogFormVisible = true;
      } else {
        this.$confirm("此操作将永久删除该图片, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(async () => {
            let { code } = await this.$Http.delImgs({ id: row.id });
            if (code) {
              this.tableData.splice(index, 1);
              this.$message({
                type: "success",
                message: "删除成功!"
              });
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      }
    },
    // 添加标签
    async addLabel(type, params) {
      this.$refs["ruleForm"].validate(async valid => {
        if (!valid) return;
        if (!this.form.content) {
          this.$message.error("请输入图文详情");
          return;
        }
        this.isBtn = true;
        let obj = Object.assign({}, this.form);
        let { code, data } = await this.$Http.setProjectTmp(obj);
        this.isBtn = false;
        if (code) {
          this.$message.success((this.form.id ? "修改" : "添加") + "成功!");
          this.GetList();
          this.dialogFormVisible = false;
          this.form = this.$options.data().form;

          this.closeDialog();
        }
      });
    },
    // 获取标签列表
    async GetList() {
      this.loading = true;
      let { code, data } = await this.$Http.getProjectTmp(this.paging);
      this.loading = false;
      if (code) {
        data.data.forEach(item => {
          item.pics = item.pics.map(item => item.pic);
        });
        this.tableData = data.data;
        // this.paging.limit =data.per_page
        this.paging.total = data.total;
      }
    },
    // 关闭弹窗
    closeDialog() {
      this.form.id = "";
      this.form.name = "";
      this.form.pic = "";
      this.form.pics = [];
      this.form.tips = "";
      this.form.desc = "";
      this.form.content = "";
      this.form.notice = "";
      // this.editor.txt.html = ''
      this.editor.txt.clear();
      // 销毁现有编辑器
      this.editor.destroy();

      this.dialogFormVisible = false;
      this.form = this.$options.data().form;
    },
    reset() {
      //重置
      this.paging = this.$options.data().paging;
      this.GetList();
    },
    // 富文本编辑
    getEdit() {
      this.editor = new E(this.$refs.edit);
      this.editor.config.onchange = html => {
        this.form.content = html;
      };
      this.editor.config.customUploadImg = (resultFiles, insertImgFn) => {
        let formData = new window.FormData();
        formData.append("files", resultFiles[0]);
        this.$Http.upload(formData).then(res => {
          if (res.status) {
            this.$message({
              message: "上传成功",
              type: "success"
            });
            insertImgFn(res.data);
          }
        });
      };
      this.editor.config.customUploadVideo = (resultFiles, insertVideoFn) => {
        let formData = new window.FormData();
        formData.append("files", resultFiles[0]);
        this.$Http.upload(formData).then(res => {
          if (res.status) {
            this.$message({
              message: "上传成功",
              type: "success"
            });
            insertVideoFn(res.data);
          }
        });
      };
      this.editor.create();
      this.editor.txt.html(this.form.content);
    }
  }
};
</script>

<style lang="scss" scoped>
.image-thumbnail {
  width: 130px;
  height: 130px;
}
</style>